using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mine : MonoBehaviour
{
    public Material material_origin;
    List<enemy> enemies;
    // Start is called before the first frame update
    void Start()
    {
        material_origin = new Material(gameObject.transform.GetComponent<Renderer>().material);
        enemies = new List<enemy>();   //初始化列表
        //获取Renderer的默认材质,赋值给material_origin变量         
    }

    // Update is called once per frame
    void Update()
    {

    }
    //鼠标悬停时调用
    private void OnMouseOver()

    {

        gameObject.transform.GetComponent<Renderer>().material.color = Color.red;
        //将Render的材质颜色设置为红色     
    }
    //鼠标退出时调用
    private void OnMouseExit()
    {
        gameObject.transform.GetComponent<Renderer>().material.color = material_origin.color;
        //将Render的材质颜色设置为material_origin的颜色
    }
    IEnumerator OnMouseDown()
    {
        //获取鼠标点击位置到相机的y坐标
        float z = Camera.main.WorldToScreenPoint(transform.position).z;
        //计算鼠标点击位置与对象位置的偏移量
        Vector3 offset = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, z)) - transform.position;
        while (Input.GetMouseButton(0))
        {
            //获取当前鼠标位置
            transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, z)) - offset;
            //设置对象位置为当前鼠标位置
            yield return new WaitForFixedUpdate();
        }
    }
    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "enemy")
        {
            enemies.Add(other.GetComponent<enemy>());
            //如果触发物体的tag为Enemy
            Debug.Log(enemies.Count);
            StartCoroutine(MoveToTarget(other.transform));
        }
    }
    void DestroyMine()
    {
        GameObject exp = Instantiate((GameObject)Resources.Load("mineExplode"));
        exp.transform.position = gameObject.transform.position;
        //将实例化的游戏对象的位置设置为敌人的位置

        ParticleSystem effect = exp.GetComponent<ParticleSystem>();
        //获取实例化游戏对象上的ParticleSystem组件

        effect.Play();
        Destroy(exp, 1f);
        Destroy(gameObject);  //销毁mine

        foreach (enemy enemy in enemies)
        {
            enemy.hp -= 1000;   //每个敌人生命值减50
        }
    }
    IEnumerator MoveToTarget(Transform target)
    {
        Vector3 startPos = transform.position;  //记录mine的初始位置
        Vector3 endPos = target.position;      //记录敌人的位置
        float time = 0;                        //时间计数
        float duration = 0.2f;                   //移动持续时间

        while (time < duration)   //当时间小于持续时间时循环
        {
             //平滑改变mine的位置
            transform.position = Vector3.Lerp(startPos, endPos, time / duration);
           
            time += Time.deltaTime;   //增加时间
            yield return null;        //返回
        }
        transform.position = endPos;  //将mine位置设置为敌人位置
        DestroyMine();
    }

}




